
import { _decorator, Component, Node, Prefab } from 'cc';
import GlobalPool, { customPoolScript } from '../../Script/Common/GlobalPool';
import yyComponent from '../../Script/Common/yyComponent';
const { ccclass, property } = _decorator;

/**水平显示的循环列表 */
@ccclass('LoopListH')
export class LoopListH extends yyComponent {

    public init(data?) {
        GlobalPool.createPool(this.itemPrefab.data.name, this.itemPrefab, "LoopListItem");
        if (!!data) {
            this.setData(data);
        }
    }

    protected setData(data: { spaceX: number, data: any[] }) {
        this.setScope(data);
        for (let i = 0, c = data.data.length; i < c; ++i) {
            this.addItem(data.data[i]);
        }
    }

    @property(Prefab)
    protected itemPrefab: Prefab = null;
    @property(Node)
    protected itemLayer: Node = null;
    protected items: Node[] = [];
    protected data: any[] = [];
    protected curPtr: number = 0;
    protected addItem(data) {
        let node = GlobalPool.get("LoopListItem", data);
        node.setPosition(this.minX + this.itemLayer.children.length * this.spaceX, 0);
        this.items.push(node);
        this.itemLayer.addChild(node);
    }

    protected minX: number;
    protected maxX: number;
    protected spaceX: number;
    protected setScope(data: { spaceX: number, data: any[] }) {
        this.spaceX = data.spaceX;
        let w = data.data.length * this.spaceX;
        this.minX = -0.5 * w;
        this.maxX = 0.5 * w;
    }
    public setOffset(offsetX: number) {
        for (let i = 0, c = this.items.length; i < c; ++i) {
            let x = this.minX + i * this.spaceX;
            x += offsetX;
            let o = this.maxX - x;
            o = this.maxX - o % (this.maxX * 2);
            x = o;
            this.items[i].setPosition(x, 0, 0);
            let s = 1 - Math.abs(x) / this.maxX;
            this.items[i].setScale(s, s, s);
        }
    }

}
